package com.ruoyi.oos.tag.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.oos.tag.domain.TagConfig;
import com.ruoyi.oos.tag.domain.TagGroup;
import com.ruoyi.oos.tag.domain.TagLimitdtl;
import com.ruoyi.oos.tag.mapper.TagConfigMapper;
import com.ruoyi.oos.tag.mapper.TagGroupMapper;
import com.ruoyi.oos.tag.mapper.TagLimitdtlMapper;
import com.ruoyi.oos.tag.service.ITagConfigService;

import cn.hz.pi.api.PiApiUtil;
import cn.hz.pi.api.util.DateUtil;
import cn.hz.pi.api.util.TagValue;

/**
 * 测点配置Service业务层处理
 * 
 * @author wzy
 * @date 2020-05-11
 */
@Service
public class TagConfigServiceImpl implements ITagConfigService 
{
    @Autowired
    private TagConfigMapper tagConfigMapper;
    
    @Autowired
    private TagLimitdtlMapper tagLimitMapper;
    
    @Autowired
    private TagGroupMapper tagGroupMapper;

    /**
     * 查询测点配置
     * 
     * @param id 测点配置ID
     * @return 测点配置
     */
    @Override
    public TagConfig selectTagConfigById(Long id)
    {
        return tagConfigMapper.selectTagConfigById(id);
    }

    /**
     * 查询测点配置列表
     * 
     * @param tagConfig 测点配置
     * @return 测点配置
     */
    @Override
    public List<TagConfig> selectTagConfigList(TagConfig tagConfig)
    {
        return tagConfigMapper.selectTagConfigList(tagConfig);
    }

    /**
     * 新增测点配置
     *  {[2020-01-01,2050-01-01]:(10,15)}
     * @param tagConfig 测点配置
     * @return 结果
     */
    @Override
    public int insertTagConfig(TagConfig tagConfig)
    {
    	int a = tagConfigMapper.insertTagConfig(tagConfig);
    	Long id = tagConfig.getId();
    	String upperval =tagConfig.getUpperval();//上线公式
    	String lowerval =tagConfig.getLowerval();//下线公式
    	String limitType =tagConfig.getLimittype();
        this.updateLimitdtl(upperval, id,1L,limitType);
        this.updateLimitdtl(lowerval, id,2L,limitType);
        return a;
    }

    /**
     * 修改测点配置
     * 
     * @param tagConfig 测点配置
     * @return 结果
     */
    @Override
    public int updateTagConfig(TagConfig tagConfig)
    {
    	Long id = tagConfig.getId();
    	TagConfig tagConfig1 = tagConfigMapper.selectTagConfigById(id);
    	String limitType =tagConfig.getLimittype();
    	String upperval =tagConfig.getUpperval();//上线公式
    	String lowerval =tagConfig.getLowerval();//下线公式
    	String upperval1 =tagConfig1.getUpperval();//上线公式
    	String lowerval1 =tagConfig1.getLowerval();//下线公式
    	if(StringUtil.isNotEmpty(upperval) && upperval.contains("{") && upperval.contains(":")  ) {
    		if(StringUtil.isNotEmpty(upperval1) && !upperval1.equals(upperval)) {
    			tagLimitMapper.deleteTagLimitdtlByConfigId(id,1);
    			this.updateLimitdtl(upperval, id, 1L,limitType);
    		}
    	}
    	if(StringUtil.isNotEmpty(lowerval) && lowerval.contains("{") && lowerval.contains(":")  ) {
    		if(StringUtil.isNotEmpty(lowerval1) && !lowerval1.equals(lowerval)) {
    			tagLimitMapper.deleteTagLimitdtlByConfigId(id,2);
    			this.updateLimitdtl(lowerval, id, 2L,limitType);
    		}
    	}
        return tagConfigMapper.updateTagConfig(tagConfig);
    }

    /**
              * 删除测点配置对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTagConfigByIds(String ids)
    {
        return tagConfigMapper.deleteTagConfigByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除测点配置信息
     * 
     * @param id 测点配置ID
     * @return 结果
     */
    public int deleteTagConfigById(Long id)
    {
        return tagConfigMapper.deleteTagConfigById(id);
    }
  
    /**
     * 更新公式
     * @param upperval
     * @param id
     * @param type
     */
    private void  updateLimitdtl(String upperval,Long id,Long type,String limitType) {
    	
    	if(limitType.equals("1") || limitType.equals("2") || limitType.equals("4") ) {
        if(StringUtils.isNotEmpty(upperval) && upperval.contains("{") && upperval.contains(":")) {
       	 upperval = upperval.replace("{", "").replace("}", "");
       	String[]  name1 = upperval.split("\\|");
       	for (String string : name1) {
   			String[] name2 = string.split(":");
   			String[] times = name2[0].split(",");
   			String[] limitvalue = name2[1].split(",");
   			int size = limitvalue.length;
   			for (int i =0; i<size;i++) {
   				TagLimitdtl limitdtl = new TagLimitdtl();
   				limitdtl.setConfigid(id);
   				limitdtl.setType(type);
   				limitdtl.setStarttime(times[0]);
   				limitdtl.setEndtime(times[1]);
   				limitdtl.setLevel(i+"");
   				limitdtl.setLimitval(Float.parseFloat(limitvalue[i]));
   				if(i+1<size) {
   					limitdtl.setEndlimitval(Float.parseFloat(limitvalue[i+1]));
   				}else if(i+1==size) {
   					limitdtl.setEndlimitval(Float.parseFloat(limitvalue[i]));
   				}
   				
   				tagLimitMapper.insertTagLimitdtl(limitdtl);
   			}
   		}
        }
    	}
    	//{[2020-01-01,2050-01-01]:<(100,30)(150,100)&>}|
    	if(limitType.equals("3")) {//动态限值
    		 if(StringUtils.isNotEmpty(upperval) && upperval.contains("{") && upperval.contains(":") ) {	
    			 upperval = upperval.replace("{", "").replace("}", "");
    				String[]  name1 = upperval.split("\\|"); 
    				for (String string : name1) {
    		   			String[] name2 = string.split(":");
    		   			String[] times = name2[0].split(",");
    		   			String tempTag =name2[1];
    		   			String[] limitvalue = name2[2].split("&");
    		   			int size = limitvalue.length;
    		   			for (int i =0; i<size;i++) {
    		   				TagLimitdtl limitdtl = new TagLimitdtl();
    		   				limitdtl.setConfigid(id);
    		   				limitdtl.setType(type);
    		   				limitdtl.setStarttime(times[0]);
    		   				limitdtl.setEndtime(times[1]);
    		   				limitdtl.setLevel(i+"");
    		   				
//    		   				limitdtl.setLimitval(Float.parseFloat(limitvalue[i]));
    		   				String limitval ="curve('"+tempTag+"',"+limitvalue[i]+")";
    		   				limitdtl.setPitag(limitval);
//    		   				if(i+1<size) {
//    		   					limitdtl.setEndlimitval(Float.parseFloat(limitvalue[i+1]));
//    		   				}else if(i+1==size) {
//    		   					limitdtl.setEndlimitval(Float.parseFloat(limitvalue[i]));
//    		   				}
    		   				
    		   				tagLimitMapper.insertTagLimitdtl(limitdtl);
    		   			}
    		   		}	
    		 }
    		
    	}
    }

	@Override
	public PiUtilBean getChartData(String tagname, String strarttime, String endtime) {
		PiUtilBean returnBean = new PiUtilBean();
		 Long allTime = DateUtil.minDataBetween(strarttime,endtime,1);
		 List<Float> retrunList = new ArrayList<Float>();
		 List<String> returntimes = new ArrayList<String>();
		 List<TagValue> list =PiApiUtil.getValueList(null,tagname,strarttime,endtime, allTime.intValue());
		 for (TagValue tagValue : list) {
			 retrunList.add(tagValue.getValue());
			 returntimes.add(tagValue.getTime());
		}
		 returnBean.setRetrunList(retrunList);
		 returnBean.setReturntimes(returntimes);
		 return returnBean;
	}

  /**
   * 查询测点的树
   * @return
   */
  public List<Ztree> selectTagTree() {
  	List<TagGroup> groupList = tagGroupMapper.selectTagGroupList(null);
  	List<TagConfig> tagList = tagConfigMapper.selectTagConfigList(null);
    List<Ztree> ztrees = initZtree(groupList, tagList);
    return ztrees;
  }
  
  /**
   * 对象转测点树
   *
   * @param groupList 测点分组列表
   * @param tagList 测点列表
   * @return 树结构列表
   */
  private List<Ztree> initZtree(List<TagGroup> groupList, List<TagConfig> tagList)
  {
      List<Ztree> ztrees = new ArrayList<Ztree>();
      // 分组转树
      for (TagGroup group : groupList)
      {
      	Ztree ztree = new Ztree();
        ztree.setId(group.getId());
        ztree.setpId(group.getPid());
        ztree.setName(group.getGroupname());
        ztree.setTitle(group.getGroupname());
        
        ztrees.add(ztree);
      }
      
      // 测点转树
      for (TagConfig tag : tagList)
      {
      	Ztree ztree = new Ztree();
        ztree.setId(tag.getId());
        ztree.setpId(tag.getGroupid());
        ztree.setName(tag.getTagname());
        ztree.setTitle(tag.getTagname());
        
        ztrees.add(ztree);
      }
      
      return ztrees;
  }
  
}
